package com.lbw.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lbw.config.Comment;
import com.lbw.entity.QuestionEntity;
import com.lbw.mapper.QuestionEntityMapper;
import com.lbw.service.QuestionEntityService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lbw
 * @since 2020-09-13
 */
@Service
public class QuestionEntityServiceImpl extends ServiceImpl<QuestionEntityMapper, QuestionEntity> implements QuestionEntityService {

    @Resource
    private QuestionEntityMapper questionEntityMapper;
    @Autowired
    private RestHighLevelClient restHighLevelClient;

    /**
     * 通过课程以及章节Id查询出题目
     * @param chapterId 章节Id
     * @param type 科目Id
     * @return 题目集合
     */
    @Override
    public List<QuestionEntity> selectQuestionByChapterAndSubject(String chapterId, Integer type) {

        // 查询条件
        LambdaQueryWrapper<QuestionEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(QuestionEntity::getChapter,chapterId)
                .eq(QuestionEntity::getType,type)
        .orderByAsc(QuestionEntity::getCommentId,QuestionEntity::getCommentPage);
        //查询
        return questionEntityMapper.selectList(lambdaQueryWrapper);
    }

    @Override
    public IPage<QuestionEntity> selectQuestionByChapterAndSubjectPage(String chapterId, Integer type, Integer pageNo, Integer pageSize) {
        // 查询条件
        LambdaQueryWrapper<QuestionEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(QuestionEntity::getChapter,chapterId)
                .eq(QuestionEntity::getType,type).orderByAsc(QuestionEntity::getCommentId,QuestionEntity::getCommentPage);
        //查询
        Page<QuestionEntity> questionEntityPage = new Page<QuestionEntity>(pageNo,pageSize);
        IPage<QuestionEntity> entityIPage = this.page(questionEntityPage, lambdaQueryWrapper);
        return entityIPage;
    }

    @Override
    public IPage<QuestionEntity> selectQuestionByKeyWord(String keyWord,Integer pageNo,Integer pageSize) {
        LambdaQueryWrapper<QuestionEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(StringUtils.isNotEmpty(keyWord),QuestionEntity::getName,keyWord);
        Page<QuestionEntity> questionEntityPage = new Page<QuestionEntity>(pageNo,pageSize);
        IPage<QuestionEntity> entityIPage = this.page(questionEntityPage, lambdaQueryWrapper);
        return entityIPage;
    }

    @Override
    public boolean insertQuestion(List<QuestionEntity> questionEntityList) throws IOException {
        if (questionEntityList != null && !questionEntityList.isEmpty()) {
            //获取第一个问题
            QuestionEntity questionEntity = questionEntityList.get(0);
            //判断问题类型
            Integer type = questionEntity.getType();
            if (type == 1) {
                //题目为行测
                return this.save(questionEntity);
            }else {
                //题目为申论
                String commentId = UUID.randomUUID().toString().replaceAll("-", "");

                //判断所属科目，如果为申论则向es中存入数据
                //先判断索引是否存在，如果存在则不创建直接添加
                GetIndexRequest getIndexRequest = new GetIndexRequest(Comment.ES_INDEX);
                boolean exists = restHighLevelClient.indices().exists(getIndexRequest, RequestOptions.DEFAULT);
                if (!exists) {
                    //如果不存在则重新创建
                    CreateIndexRequest createIndexRequest = new CreateIndexRequest(Comment.ES_INDEX);
                    restHighLevelClient.indices().create(createIndexRequest, RequestOptions.DEFAULT);
                }
                LinkedList<QuestionEntity> questionEntityLinkedList = new LinkedList<>();
                BulkRequest bulkRequest = new BulkRequest();
                bulkRequest.timeout("20s");
                for (QuestionEntity question : questionEntityList) {
                    String id = UUID.randomUUID().toString().replaceAll("-", "");
                    question.setId(id);
                    question.setCommentId(commentId);
                    //批量新增，删除、更新都在此操作
                    bulkRequest.add(new IndexRequest(Comment.ES_INDEX)
                            .id(id).source(JSON.toJSONString(question), XContentType.JSON));
                    questionEntityLinkedList.add(question);
                }
                BulkResponse bulkResponse = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
                return this.saveBatch(questionEntityLinkedList);
            }
        }
        return false;
    }
}
